<template>
  <d2-container>
  <div class="app-container">
    <el-container :style="'height:'+containerHeight+'px'">
      <el-main class="theme-front-color">
        <el-row>
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <div style="font-size:15px;display:inline-block; float:left;">
                <el-form-item label="分类" label-width="40px">
                  <el-select v-model="dataForm.energyType"  style="width: 90px;" placeholder="请选择"  size="mini" @change="queryCollectType">
                    <el-option
                      v-for="(item, index) in meterTypeList" :key="index"
                      :label="item.paramValue"
                      :value="item.paramKey">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="采集项" label-width="60px">
                  <el-select v-model="dataForm.collectType"  style="width: 120px;" placeholder="请选择"  size="mini">
                    <el-option
                      v-for="(item, index) in collectTypeList" :key="index"
                      :label="item.collectName"
                      :value="item.collectType">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="日期" label-width="40px">
                    <el-date-picker
                      v-model="dataForm.date"
                      placeholder="时间范围"
                      style="width: 130px;"
                      class="filter-item"
                      size="mini"
                      :type="dataForm.dateType"
                      suffix-icon="el-icon-date"
                      clearable
                      @keyup.enter.native="getPowerDataList"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-radio-group v-model="dataForm.dateType" size="mini">
                      <el-radio-button :label="item.date" v-for="(item, index) in Config.searchDate" :key="index">
                        {{item.label}}
                      </el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item >
                  <el-checkbox v-model="dataForm.flag" label="1">按计量器汇总</el-checkbox>
                </el-form-item>
                <el-form-item >
                  <el-checkbox v-model="dataForm.fenbiaoflag" label="1">是否展示分表</el-checkbox>
                </el-form-item>
              </div>
              <div style="display:inline-block; float:right;">
                <el-form-item>
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getPowerDataList"
                  >查询</el-button>
                  <el-button
                      class="filter-item"
                      type="primary"
                      icon="el-icon-download"
                      size="mini"
                      @click="exoprtData"
                  >导出</el-button>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-row>
        <div style="margin-top:20px;">
          <el-row>
            <el-col :span="24" style="width: 100%;overflow:auto;" >
              <el-table :data="dataList" :height="chartHeight" show-summary border style="width: 100%;overflow:visible;" :summary-method="getSummaries">
                <!-- <el-table-column prop="index" header-align="center" align="center"  width="70" label="序号"></el-table-column> -->
                <el-table-column
                  prop="ObjName"
                  header-align="center"
                  align="center"
                  label="归属"
                ></el-table-column>
                <el-table-column
                  prop="meterTypeName"
                  header-align="center"
                  align="center"
                  label="分类"
                  width="70"
                ></el-table-column>
                <el-table-column
                  prop="meterName"
                  header-align="center"
                  align="center"
                  label="计量器具名称"
                ></el-table-column>
                <el-table-column
                  prop="date"
                  header-align="center"
                  align="center"
                  label="时间"
                ></el-table-column>
                <el-table-column
                  prop="startval"
                  header-align="center"
                  align="center"
                  label="起始值"
                ></el-table-column>
                <el-table-column
                  prop="endval"
                  header-align="center"
                  align="center"
                  label="终止值"
                ></el-table-column>
                <el-table-column
                  prop="val"
                  header-align="center"
                  align="center"
                  :label="`用量(${unit})`"
                ></el-table-column>
                <el-table-column
                  prop="fee"
                  header-align="center"
                  align="center"
                  label="费用(元)"
                ></el-table-column>
              </el-table>
              <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="page.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.size"
                :total="page.total"
                layout="total, sizes, prev, pager, next, jumper">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </el-main>
      <el-aside class="tree-area">
        <el-tabs v-model="activeName">
          <el-tab-pane label="区域" name="2">
            <el-button
              class="filter-item"
              size="mini"
              @click="checkAllArea"
            >全选</el-button>
            <el-button
              class="filter-item"
              size="mini"
              @click="resetCheckedArea"
            >清空</el-button>
             <el-tree style="margin-top: 10px"
                ref="buildTree"
                :show-checkbox="true"
                highlight-current
                node-key="buildingId"
                :check-on-click-node="true"
                :check-strictly="false"
                :data="dataBuildingList"
                :expand-on-click-node="false"
                :props="buildTreeProps"
                @check="selectBuild"
                default-expand-all
              ></el-tree>
          </el-tab-pane>
          <el-tab-pane label="部门" name="3">
            <el-button
              class="filter-item"
              size="mini"
              @click="checkAllDepart"
            >全选</el-button>
            <el-button
              class="filter-item"
              size="mini"
              @click="resetCheckedDepart"
            >清空</el-button>
             <el-tree  style="margin-top: 10px"
                ref="departTree"
                highlight-current
                :show-checkbox="true"
                node-key="organizationId"
                :data="dataOrgList"
                :check-strictly="true"
                :check-on-click-node="true"
                :expand-on-click-node="false"
                :props="orgTreeProps"
                @check="selectDepart"
                default-expand-all
              ></el-tree>
          </el-tab-pane>
        </el-tabs>

      </el-aside>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import * as Echarts from 'echarts'
import Config from "@/utils/config"
import Minix from '../power/mixin'
export default {
  name: "areaPage",
  mixins:[Minix],
  data() {
    return {
      Config:Config,
      activeName:'2',
      dataForm: {
        date:new Date(),
        dateType:'date',
        energyType:this.$meterType.ELECTRIC,
        collectType:'',
        flag:'',
        fenbiaoflag:''
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      buildTreeProps: {
        label: "buildingName",
        children: "children"
      },
      orgTreeProps: {
        label: "organizationName",
        children: "children"
      },
      unit:'',
      dataList:[],
      dataBuildingList: [],
      dataBuildingListSrc: [],
      dataOrgList:[],
      dataOrgListSrc:[],
      meterTypeList:[],
      collectTypeList:[],
      currentSelectBuildInfoList:[],
      currentSelectDepartInfoList:[],
      departTableDataList:[],
      sourceData:[],
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 325;
    }
  },
  created() {
    this.queryStatic("METER_TYPE");
    this.getDepartList();
    this.getBuildInfoList();
  },
  methods: {
    checkAllArea() {
      this.$refs.buildTree.setCheckedNodes(this.dataBuildingListSrc);
      this.selectBuild()
    },
    checkAllDepart() {
      this.$refs.departTree.setCheckedNodes(this.dataOrgListSrc);
      this.selectDepart()
    },
    resetCheckedArea() {
      this.$refs.buildTree.setCheckedKeys([]);
      this.selectBuild()
    },
    resetCheckedDepart() {
      this.$refs.departTree.setCheckedKeys([]);
      this.selectDepart()
    },

    /**
     * 获取采集分项
     */
    queryCollectType() {
      let params = {
        'meterType': this.dataForm.energyType ,
        'state': '1' ,
        'cumulativeType':'1',
        "customerId":this.$util.cookies.get('customer_id'),
        'page': 1,
        'limit': 10000,
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecs/ecscollectitem/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
          if (data && data.code === 0) {
          this.collectTypeList = data.page.list
          this.dataForm.collectType = data.page.list[0].collectType;
          if(data.page.list[0].collectUnit !=='') {
            this.unit = data.page.list[0].collectUnit;
          }
        } else {
          this.collectTypeList = []
        }
      });
    },
    sizeChangeHandle(size){
      this.page.size = size;
      this.handleDataList();
    },
    currentChangeHandle(page){
      this.page.page = page;
      this.handleDataList();
    },
    exoprtData(){
      let header=['归属名称','分类','计量器具名称','计量器具编码','时间','起始值','终止值',`用量(${this.unit})`,'费用(元)'];
      let props=['ObjName','meterTypeName','meterName','meterCode','date','startval','endval','val','fee'];
      let fileName=`用${this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`;
      this.export2Excel(header,props,fileName,this.sourceData)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = JSON.parse(JSON.stringify(dataList));
      let sumVal = list.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.val;
      }, 0);
      let sumfee = list.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.fee;
      }, 0);
      list.push({
        "ObjName":'合计',
        "val":sumVal,
        "fee":sumfee
      })

        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    getSummaries(param) {
      const { columns, data } = param;
      let sumVal = this.sourceData.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.val;
      }, 0);
      let sumfee = this.sourceData.reduce(function (total, currentValue, currentIndex, arr) {
        return total + currentValue.fee;
      }, 0);
      return ['合计','','','','','',sumVal.toFixed(2),sumfee.toFixed(2)];
    },
    //选中部门
    selectDepart(){
      this.currentSelectDepartInfoList = this.$refs.departTree.getCheckedNodes();
    },
    //选中设备
    selectBuild(){
      this.currentSelectBuildInfoList = this.$refs.buildTree.getCheckedNodes();
    },
    // 获取区域树
    getBuildInfoList() {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          customerId: this.$util.cookies.get("customer_id"),
          projectid:this.$util.cookies.get("cuuren_projectId")
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataBuildingListSrc = data.menuList
          this.dataBuildingList =  Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
        } else {
          this.dataBuildingList = [];
        }
      });
    },
    // 获取部门数据列表
    getDepartList () {
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsorganizationinfo/select"),
        method: 'get',
        params: this.$http.adornParams({
          'page': 1,
          'limit': 10000,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.dataOrgListSrc = data.menuList
          this.dataOrgList =Util.treeDataTranslate(data.menuList,'organizationId','parentOrgId')
        } else {
          this.dataOrgList = []
        }
      })
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.unit = data.page[0].paramExt;
          this.queryCollectType()
        } else {
          this.meterTypeList = []
        }
       // this.getDataList();
      });
    },
    getPowerDataList() {
      this.page.page = 1;
      this.sourceData = [];
      this.dataList = [];
      let currentSelectInfo = [];
       if(this.activeName=='2'){
          if(this.currentSelectBuildInfoList&&this.currentSelectBuildInfoList.length>0){
            this.currentSelectBuildInfoList.forEach(ele=>{
                currentSelectInfo.push(ele.buildingId);
            })
          }
       }
       else{
          if(this.currentSelectDepartInfoList&&this.currentSelectDepartInfoList.length>0){
            this.currentSelectDepartInfoList.forEach(ele=>{
              currentSelectInfo.push(ele.organizationId);
            })
          }
      }
      let params = {
          flag:this.dataForm.flag?"1":"0",
          fenbiaoflag:this.dataForm.fenbiaoflag?"1":"0",
          customerId: this.$util.cookies.get("customer_id"),
          meterType:this.dataForm.energyType , //能耗分类
          collectType:this.dataForm.collectType ,
          objType: this.activeName,    //对象类型  2:区域 3:部门
          objIds:currentSelectInfo,    //对象id
          dateType :parseInt(this.Config.searchDate.find(ele=>ele.date==this.dataForm.dateType).typeDesc)+2,// 3:按天, 4:按月 5:年
          date:Util.dateFormat(this.Config.searchDate.find(ele=>ele.date==this.dataForm.dateType).formatStr,new Date(this.dataForm.date)), //日期
          // objIds: [7,9],
          // date: '2020-06',
          // dateType: '4',
          // objType: '2',
          // meterType: '1',
          // customerId: this.$util.cookies.get("customer_id")

      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecm/report/list'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then((data) => {
        if (data && data.code === 0) {
          //console.log('所有数据',data.data)
          if(data.data&&data.data.length>0){
            this.sourceData =data.data;
            if(this.sourceData.length>0){
              this.page.total = this.sourceData.length;
              this.sourceData.forEach(ele=>{
                ele.meterTypeName = this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue;
              })
            }
            else{
              this.page.total =0;
              this.dataList = [];
            }
            this.handleDataList()
          }
        }
      });
    },
    handleDataList(){
      if(this.sourceData.length>0){
        let totalPage = Math.ceil(this.sourceData.length/this.page.size);
        if(this.page.page<=totalPage){
          if(this.page.page*this.page.size>=this.sourceData.length){
             this.dataList = this.sourceData.slice((this.page.page-1)*this.page.size,this.sourceData.length);
          }
          else{
            this.dataList = this.sourceData.slice((this.page.page-1)*this.page.size,this.page.page*this.page.size);
          }
        }
      }
    }
  },
  watch:{
    'dataForm.energyType':function(newV,oldV){
      this.unit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
  }
};
</script>

<style scoped>
.tree-area { background-color: rgba(0, 0, 0, 0.1);
  width: 250px !important;
  /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
  /* border: solid 1px #808080; */
  padding-top: 10px;
  padding-left: 15px;
}
.bg-white {
  box-shadow: 0px 0px 2px 2px #f7f6f6;
}
.el-tree-node__content {
  height: 30px !important;
}
.busi-chart{
    width: 100%;
    height: 250px;
    margin-top: 10x;
    margin-bottom: 20px;
}
.el-form-item{
  margin-bottom: 0px;
}
.search-area{
   display:flow-root;
   margin-bottom: 10px;
   border: 1px solid #808080;
   border-left: none;
   border-right: none;
   padding: 10px 0px 10px 0px;
}
</style>
